//
//  MainTabBarViewController.swift
//  mySwift
//
//  Created by 高赛 on 16/9/14.
//  Copyright © 2016年 高赛. All rights reserved.
//

import UIKit

class MainTabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        // 设置当前控制器对应tabbar的颜色
        // 注意:iOS7以前如果设置了tintColor只有文字会改变,图片不会,如果要修改图片不被系统渲染可以在图片的Render As设置为Original Image即可
        // 在appleDelegate里面设置  appearance外观 全局有效 要在程序入口处设置
//        tabBar.tintColor = UIColor.orange
        
        // 添加子控制器
        addChildViewControllers()
        
        // 在iOS7以后就不推荐在ViewDidLoad里面设置frame
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        setUpComposeBtn()
        
    }
    
    func clickComposeBtn()
    {
        print("sdafsdf")
    }
    
    private func setUpComposeBtn()
    {
        // 添加加号按钮
        tabBar.addSubview(composeBtn)
        // 调整按钮位置
        let width = UIScreen.main.bounds.size.width / CGFloat(viewControllers!.count)
        let height = 49
        let rect = CGRect(x: 0, y: 0, width: Int(width), height: Int(height))
        composeBtn.frame = rect.offsetBy(dx: 2 * width, dy: 0)
        
    }
    
    
    private func addChildViewControllers() {
        // 加载本地数据,模拟网络请求 动态创建控制器
        let path = Bundle.main.path(forResource: "MainVCSettings", ofType: "json")
        if let jsonPath = path{
            let jsonData = NSData.init(contentsOfFile: jsonPath)
            do{
                // 有可能发生异常的代码
                // try 发生异常会跳到catch中继续执行
                // tyr! 发生异常会直接崩溃
                let dictArr = try JSONSerialization.jsonObject(with: jsonData! as Data, options:JSONSerialization.ReadingOptions.mutableContainers)
                // 确定dictArr的类型为数组加字典
                for dict in dictArr as! [[String: String]]{
                    // 报错的原因是addChildViewController的参数必须有值,但字典的返回值是可选的,所以必须告诉他一定有值
                    addChildViewController(dict["vcName"]!, image: dict["imageName"]!, title: dict["title"]!)
                }
            }catch{
                // 发生异常后会执行的代码
                print(error)
                // 如果报错就用写死的代码来创建
                // 使用动态加载控制器
                // 通过字符串来创建控制器,,用于动态初始化控制器
                //                addChildViewController("HomeTableViewController", image: "tabbar_home", title: "首页")
                addChildViewController(HomeTableViewController(), image: "tabbar_home", title: "首页")
                
                addChildViewController(MessageTableViewController(), image: "tabbar_message_center", title: "消息")
                
                addChildViewController(NullViewController(), image: "", title: "")
                
                addChildViewController(DiscoverTableViewController(), image: "tabbar_discover", title: "广场")
                
                addChildViewController(ProfileTableViewController(), image: "tabbar_profile", title: "我")
            }
        }
    }
    
    private func addChildViewController(_ childController: UIViewController, image: String, title: String) {

        // 1.设置标题
        childController.title = title
        // 2.设置图片
        childController.tabBarItem.image = UIImage(named: image)
        childController.tabBarItem.selectedImage = UIImage(named: image + "highlighted")
        // 3.包装导航条
        let nav = UINavigationController()
        nav.addChildViewController(childController)
        // 4.添加到tabbar
        addChildViewController(nav)
        
    }
    
    private func addChildViewController(_ childControllerName: String, image: String, title: String) {
        
        // 1.动态初始化类  NSClassFromString通过字符串返回类
        // mySwift为命名空间,一般为项目项目名称/  如果要修改在BUulid Settings-product name 中修改
        // 因此要动态的获取命名空间
        // !表示这个字典一定有值  前面用!表示CFBundleExecutable一定有值了,,后面也要用!表示一定是string
        let ns = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
        // 根据动态获取的命名空间去获取类名
        let cls:AnyClass? = NSClassFromString(ns + "." + childControllerName)
        // 通过类来创建对象
        // 将AnyClass转换为指定的类型
        let vcCls = cls as! UIViewController.Type
        // 通过class创建对象
        let vc = vcCls.init()
        
        // 1.设置标题
        vc.title = title
        // 2.设置图片
        vc.tabBarItem.image = UIImage(named: image)
        vc.tabBarItem.selectedImage = UIImage(named: image + "highlighted")
        // 3.包装导航条
        let nav = UINavigationController()
        nav.addChildViewController(vc)
        // 4.添加到tabbar
        addChildViewController(nav)
        
    }
    
    // MARK: --懒加载
    private lazy var composeBtn: UIButton = {
        let btn = UIButton()
        // 设置前景图片
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: UIControlState.normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        // 监听的方法不能为私有方法
        btn.addTarget(self, action: #selector(MainTabBarViewController.clickComposeBtn), for: UIControlEvents.touchUpInside)
        return btn
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
